Skip to main content

Joining on data

Consecutive for loops can be used to join between data

Advanced traversals

  1. Variables using let may be defined for various reasons, including code readability

  2. Sometimes it becomes complex or even impossible to put the whole query in a single nested combination of for loops, filters and sorts.

  3. Often, it’s easier to extract some data separately. That’s where LET comes in.

  4. Say we want to find out options to get to SFO in 2 stops starting from Tampa International (TPA) to San Francisco International (SFO), we could first find out which airports can be reached directly from TPA, then for each of these do a separate query to see which of those go to SFO.

  5. Here is one way to get to the end goal:

    let hops = (
    for f IN flights
    filter f._from == 'airports/TPA'

    return distinct {"_from":f._from, "_to":f._to, "Distance": f.Distance})
  6. Now that we have all flights going out from Tampa International(TPA), we can determine which flights go to SFO

    for h IN hops
    for f IN flights
    filter f._to == 'airports/SFO'
    filter f._from == h._to
    let journey = {
    "Path": CONCAT_SEPARATOR(" -> ",h._from,f._from,f._to),
    "Distance Total": (h.Distance + f.Distance),
    "Distance Leg1": h.Distance,
    "Distance Leg2": f.Distance
    }
    sort journey.`Distance Total` desc, journey.`Distance Leg2` desc, journey.`Distance Leg1` desc

    return distinct journey
  7. Here is a snippet of the expected results:

    [
    {
    "Path": "airports/TPA -> airports/BOS -> airports/SFO",
    "Distance Total": 3889,
    "Distance Leg1": 1185,
    "Distance Leg2": 2704
    },
    {
    "Path": "airports/TPA -> airports/JFK -> airports/SFO",
    "Distance Total": 3591,
    "Distance Leg1": 1005,
    "Distance Leg2": 2586
    },
    {
    "Path": "airports/TPA -> airports/EWR -> airports/SFO",
    "Distance Total": 3563,
    "Distance Leg1": 998,
    "Distance Leg2": 2565
    },
    {
    "Path": "airports/TPA -> airports/PHL -> airports/SFO",
    "Distance Total": 3441,
    "Distance Leg1": 920,
    "Distance Leg2": 2521
    },
    {
    "Path": "airports/TPA -> airports/BWI -> airports/SFO",
    "Distance Total": 3299,
    "Distance Leg1": 842,
    "Distance Leg2": 2457
    },
    {
    "Path": "airports/TPA -> airports/IAD -> airports/SFO",
    "Distance Total": 3229,
    "Distance Leg1": 810,
    "Distance Leg2": 2419
    },
    {
    "Path": "airports/TPA -> airports/PIT -> airports/SFO",
    "Distance Total": 3127,
    "Distance Leg1": 873,
    "Distance Leg2": 2254
    },

Clearly, some of these options may be poor from an actual schedule because we are only considering distance and not flight schedules

 
Help us improve

Anything unclear or buggy in this tutorial? Provide Feedback